package com.loan.market.util

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorInt
import com.loan.market.R
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale

fun String?.getBigDecimalSafe(def: BigDecimal = BigDecimal.ZERO): BigDecimal {
    return this?.toBigDecimalOrNull() ?: def
}

fun String?.formatAmount(max: Int = 2, format: Boolean = true, min: Int = 2): String {
    if (isNullOrEmpty()) {
        return "–"
    }
    val amount = toBigDecimalOrNull() ?: return this
    return amount.format(max, format, min)
}

fun BigDecimal.format(max: Int = 2, format: Boolean = true, min: Int = 2): String {
    return DecimalFormat().apply {
        if (format) {
            decimalFormatSymbols = DecimalFormatSymbols(Locale("es", "ar"))
            groupingSize = 3
        } else {
            groupingSize = 0
        }
        maximumFractionDigits = max
        minimumFractionDigits = min
        roundingMode = RoundingMode.HALF_UP
    }.format(this)
}

fun String?.isNotNullOrEmpty(): Boolean {
    return !isNullOrBlank()
}

fun getClickText(text: String, @ColorInt color: Int, click: () -> Unit = {}): SpannableString {
    val span = SpannableString(text)
    span.setSpan(object : ClickableSpan() {

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = color
            ds.isUnderlineText = true
        }

        override fun onClick(widget: View) {
            click()
        }

    }, 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    return span
}

fun TextView.appendClickText(text: String, @ColorInt color: Int = context.getColor(R.color.color_accent), click: () -> Unit = {}) {
    append(getClickText(text, color, click))
    highlightColor = Color.TRANSPARENT
    movementMethod = LinkMovementMethod.getInstance()
}